package com.msh.automatic.android.control.task

import android.content.ComponentName
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.util.Log
import androidx.core.content.FileProvider
import cn.hutool.http.HttpUtil
import com.alibaba.fastjson2.JSON
import com.msh.automatic.android.control.service.AIAccessibilityService
import com.msh.automatic.android.control.service.MqttService
import com.msh.automatic.android.control.task.TaskManager.TAG
import com.msh.automatic.android.control.util.AccessibilityServiceUtil
import com.msh.automatic.android.control.util.ConfigUtil
import com.msh.automatic.android.control.util.DeviceUtil
import kotlinx.coroutines.delay
import java.io.File


class AppTask(
    val task: Task,
    val taskLog: TaskLog
) {
    fun getId():String{
        return taskLog.id
    }
    suspend fun start(): Boolean{
        Log.i(TAG,"log execute: ${getId()}")
        // 判断app安装状态
        val appStatus = isInstallApp()
        if(appStatus == AppInstallStatus.VERSION_MISMATCH) {
            // 已安装，版本不匹配
            if(!unInstallApp()){
                return false
            }
        }else if(appStatus == AppInstallStatus.NOT_INSTALLED) {
            // 未安装
            if(!installApp()){
                return false
            }
        }
        // 检查无障碍服务
        if(!checkAccessibilityService()){
            return false
        }
        val that = this
        val launchIntent = Intent().apply {
            component = ComponentName(
                that.task.packageName,  // 目标包名
                that.task.activityClass  // 目标Activity类名
            )
            putExtra("task", JSON.toJSONString(that.task))
            putExtra("taskLog", JSON.toJSONString(that.taskLog))
            putExtra("token", ConfigUtil.getToken())
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }

        try {
            Log.i(TAG,"startActivity: ${launchIntent.getStringExtra("taskLog")}")
            MqttService.mqttService.startActivity(launchIntent)
            for (i in 0..3) {
                delay(300)  // 30秒
                if(AIAccessibilityService.aiAccessibilityService.currentPackage.equals("com.miui.securitycenter")  && AIAccessibilityService.aiAccessibilityService.currentActivity.equals("com.miui.wakepath.ui.ConfirmStartActivity")){
                    if(!AccessibilityServiceUtil.clickByText(AIAccessibilityService.aiAccessibilityService,"允许")){
                        this.taskLog.status=TaskLog.TaskLogStatus.over
                        this.taskLog.message = "启动app 出现小米安全提示，点击允许失败 【已下载的应用】 [${AIAccessibilityService.aiAccessibilityService.currentPackage}][${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
                        return false
                    }
                    return true
                }
            }
            return true
        } catch (e: Exception) {
            this.taskLog.status=TaskLog.TaskLogStatus.over
            this.taskLog.message = "启动脚本app失败. "+e.message
            Log.i(this.taskLog.id,this.taskLog.message ,e)
            return false
        }
        return true
    }
    suspend fun checkAccessibilityService():Boolean{
        val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        MqttService.mqttService.startActivity(intent)
        if(!AIAccessibilityService.isInit){
            this.taskLog.status=TaskLog.TaskLogStatus.over
            this.taskLog.message = "无障碍服务未打开。"
            return false
        }
        if(!AccessibilityServiceUtil.waitActivity(AIAccessibilityService.aiAccessibilityService,"com.android.settings","com.android.settings.accessibility.MiuiAccessibilitySettingsActivity",3)){
            this.taskLog.status=TaskLog.TaskLogStatus.over
            this.taskLog.message = "等待无障碍设置界面失败,[${AIAccessibilityService.aiAccessibilityService.currentPackage}][${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
            return false
        }

        if(!AccessibilityServiceUtil.clickByText(AIAccessibilityService.aiAccessibilityService,"已下载的应用")){
            this.taskLog.status=TaskLog.TaskLogStatus.over
            this.taskLog.message = "无障碍设置界面失找不到 【已下载的应用】 [${AIAccessibilityService.aiAccessibilityService.currentPackage}][${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
            return false
        }
        if(!AccessibilityServiceUtil.waitActivity(AIAccessibilityService.aiAccessibilityService,"com.android.settings","com.android.settings.SubSettings",3)){
            this.taskLog.status=TaskLog.TaskLogStatus.over
            this.taskLog.message = "等待已下载的应用界面失败,[${AIAccessibilityService.aiAccessibilityService.currentPackage}][${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
            return false
        }

        var nodes = AccessibilityServiceUtil.findAccessibilityNodeInfosByText(AIAccessibilityService.aiAccessibilityService,this.task.accessibilityServiceName)
        if(nodes.isEmpty()){
            this.taskLog.status=TaskLog.TaskLogStatus.over
            this.taskLog.message = "等待已下载的应用界面找不到无障碍服务[${this.task.accessibilityServiceName}],[${AIAccessibilityService.aiAccessibilityService.currentPackage}][${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
            return false
        }
        var status = "";
        if(nodes.get(0).parent.childCount == 3) {
            status = nodes.get(0).parent.getChild(2).text.toString()
        }else{
            status =  nodes.get(0).parent.parent.getChild(2).getChild(0).getChild(0).text.toString()
        }
        if(!status.equals("已开启")){
            if(!AccessibilityServiceUtil.clickByText(AIAccessibilityService.aiAccessibilityService,this.task.accessibilityServiceName)){
                this.taskLog.status=TaskLog.TaskLogStatus.over
                this.taskLog.message = "等待已下载的应用界面找不到无障碍服务[${this.task.accessibilityServiceName}] 无法点击,[${AIAccessibilityService.aiAccessibilityService.currentPackage}][${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
                return false
            }
            var node = AccessibilityServiceUtil.findAccessibilityNodeInfosByText(AIAccessibilityService.aiAccessibilityService,"使用"+this.task.accessibilityServiceName).get(0)
            if(node.parent.getChild(1).stateDescription!!.equals("开启")){
                AccessibilityServiceUtil.clickByNode(AIAccessibilityService.aiAccessibilityService,node)
                nodes = AccessibilityServiceUtil.findAccessibilityNodeInfosByText(AIAccessibilityService.aiAccessibilityService,"停止").filter { n->n.text.equals("停止") }
                if(!AccessibilityServiceUtil.clickByNode(AIAccessibilityService.aiAccessibilityService,nodes.get(0))){
                    this.taskLog.status=TaskLog.TaskLogStatus.over
                    this.taskLog.message = "等待已下载的应用界面找不到无障碍服务[${this.task.accessibilityServiceName}] 无法点击,[${AIAccessibilityService.aiAccessibilityService.currentPackage}][${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
                    return false
                }
            }

            if(!AccessibilityServiceUtil.clickByText(AIAccessibilityService.aiAccessibilityService,"使用"+this.task.accessibilityServiceName)){
                this.taskLog.status=TaskLog.TaskLogStatus.over
                this.taskLog.message = "等待已下载的应用界面找不到无障碍服务[${this.task.accessibilityServiceName}] 无法点击,[${AIAccessibilityService.aiAccessibilityService.currentPackage}][${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
                return false
            }

            if(!AccessibilityServiceUtil.waitActivity(AIAccessibilityService.aiAccessibilityService,"com.miui.securitycenter","com.miui.permcenter.privacymanager.SpecialPermissionInterceptActivity",3)){
                this.taskLog.status=TaskLog.TaskLogStatus.over
                this.taskLog.message = "等待无障碍警告界面失败,[${AIAccessibilityService.aiAccessibilityService.currentPackage}][${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
                return false
            }

            if(!AccessibilityServiceUtil.clickByText(AIAccessibilityService.aiAccessibilityService,"我已知晓可能存在的风险，并自愿承担可能导致的后果")){
                this.taskLog.status=TaskLog.TaskLogStatus.over
                this.taskLog.message = "点击无障碍警告界面提示错误. [${this.task.accessibilityServiceName}] [${AIAccessibilityService.aiAccessibilityService.currentPackage}][${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
                return false
            }
            delay(10_000)  // 10秒
            if(!AccessibilityServiceUtil.clickByText(AIAccessibilityService.aiAccessibilityService,"确定")){
                this.taskLog.status=TaskLog.TaskLogStatus.over
                this.taskLog.message = "点击无障碍警告界面确定错误. [${this.task.accessibilityServiceName}] 无法点击,[${AIAccessibilityService.aiAccessibilityService.currentPackage}][${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
                return false
            }
        }
        AccessibilityServiceUtil.goHome(AIAccessibilityService.aiAccessibilityService)

        if(!AccessibilityServiceUtil.waitActivity(AIAccessibilityService.aiAccessibilityService,"com.msh.automatic.android.control","com.msh.automatic.android.control.MainActivity",3)){
            this.taskLog.status=TaskLog.TaskLogStatus.over
            this.taskLog.message = "等待home界面失败,[${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
            return false
        }
        return true
    }
    suspend fun installApp():Boolean{
        val apkFile = File(MqttService.mqttService.filesDir.absoluteFile,"${this.task.packageName}.${this.task.versionCode}.apk")
        if(apkFile.exists()){
           apkFile.delete()
        }
        HttpUtil.downloadFile(this.task.downloadUrl, apkFile)
        val context = MqttService.mqttService
        val apkUri: Uri = FileProvider.getUriForFile(
            context,
            "${context.packageName}.fileprovider",
            apkFile
        )

        val intent = Intent(Intent.ACTION_VIEW).apply {
            setDataAndType(apkUri, "application/vnd.android.package-archive")
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK)
        }
        context.startActivity(intent)

        if(!AccessibilityServiceUtil.waitActivity(AIAccessibilityService.aiAccessibilityService,"com.miui.packageinstaller","com.miui.packageInstaller.NewInstallerPrepareActivity",3)){
            this.taskLog.status=TaskLog.TaskLogStatus.over
            this.taskLog.message = "等待安装界面失败,[${AIAccessibilityService.aiAccessibilityService.currentPackage}][${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
            return false
        }
        if(!AccessibilityServiceUtil.clickByText(AIAccessibilityService.aiAccessibilityService,"继续安装")){
            this.taskLog.status=TaskLog.TaskLogStatus.over
            this.taskLog.message = "安装界面失找不到 【继续安装】 [${AIAccessibilityService.aiAccessibilityService.currentPackage}][${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
            return false
        }

        if(!AccessibilityServiceUtil.waitActivity(AIAccessibilityService.aiAccessibilityService,"com.miui.packageinstaller","com.miui.packageInstaller.ui.normalmode.InstallProgressActivity",3)){
            this.taskLog.status=TaskLog.TaskLogStatus.over
            this.taskLog.message = "等待安装完成界面失败,[${AIAccessibilityService.aiAccessibilityService.currentPackage}][${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
            return false
        }

        if(!AccessibilityServiceUtil.clickByText(AIAccessibilityService.aiAccessibilityService,"完成")){
            this.taskLog.status=TaskLog.TaskLogStatus.over
            this.taskLog.message = "安装完成界面失找不到 【完成】 [${AIAccessibilityService.aiAccessibilityService.currentPackage}][${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
            return false
        }
        return true
    }
    suspend fun unInstallApp():Boolean{
        val intent = Intent(Intent.ACTION_DELETE)
        intent.data = Uri.parse("package:${this.task.packageName}")
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        MqttService.mqttService.startActivity(intent)

        if(!AccessibilityServiceUtil.waitActivity(AIAccessibilityService.aiAccessibilityService,"com.miui.packageinstaller","com.android.packageinstaller.UninstallerActivity",3)){
            this.taskLog.status=TaskLog.TaskLogStatus.over
            this.taskLog.message = "等待卸载界面失败,[${AIAccessibilityService.aiAccessibilityService.currentPackage}][${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
            return false
        }
        if(!AccessibilityServiceUtil.clickByText(AIAccessibilityService.aiAccessibilityService,"确定")){
            this.taskLog.status=TaskLog.TaskLogStatus.over
            this.taskLog.message = "卸载界面失找不到 【确定】 [${AIAccessibilityService.aiAccessibilityService.currentPackage}][${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
            return false
        }

        if(!AccessibilityServiceUtil.waitActivity(AIAccessibilityService.aiAccessibilityService,"com.miui.packageinstaller","com.android.packageinstaller.UninstallAppProgress",3)){
            this.taskLog.status=TaskLog.TaskLogStatus.over
            this.taskLog.message = "等待卸载完成界面失败,[${AIAccessibilityService.aiAccessibilityService.currentPackage}][${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
            return false
        }

        if(!AccessibilityServiceUtil.clickByText(AIAccessibilityService.aiAccessibilityService,"确定")){
            this.taskLog.status=TaskLog.TaskLogStatus.over
            this.taskLog.message = "卸载完成界面失找不到 【确定】 [${AIAccessibilityService.aiAccessibilityService.currentPackage}][${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
            return false
        }

        if(!AccessibilityServiceUtil.waitActivity(AIAccessibilityService.aiAccessibilityService,"com.msh.automatic.android.control","com.msh.automatic.android.control.MainActivity",3)){
            this.taskLog.status=TaskLog.TaskLogStatus.over
            this.taskLog.message = "等待卸载完成界面返回失败,[${AIAccessibilityService.aiAccessibilityService.currentPackage}][${AIAccessibilityService.aiAccessibilityService.currentActivity}]"
            return false
        }
        return installApp()
    }
    fun isInstallApp():AppInstallStatus{
        val pm = MqttService.mqttService.packageManager
        val packages = pm.getInstalledPackages(0)
        for (pkg in packages) {
            if (pkg.packageName == this.task.packageName) {
                return if (pkg.longVersionCode == this.task.versionCode) {
                    AppInstallStatus.INSTALLED
                } else {
                    AppInstallStatus.VERSION_MISMATCH
                }
            }
        }
        return AppInstallStatus.NOT_INSTALLED
    }
}

enum class AppInstallStatus(val label: String) {
    NOT_INSTALLED("未安装"),
    VERSION_MISMATCH("版本不匹配"),
    INSTALLED("已安装");

    override fun toString(): String = label
}
